<template>


  <div style="display:flex;flex-direction:column;justify-content:center;align-items:center;">

    <el-card class="info-card">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <h2>创建课程</h2>
          <el-button type="primary" round size="large" @click="$router.go(-1)">返回</el-button>

        </div>
      </template>

      <div style="display: flex;flex-direction: column; align-items: center; ">

        <div style="display: flex; flex-direction: column; align-items: center; margin-bottom:40px">
          <UploadCover v-model="form.img" />
        </div>


        <div style="display: flex; flex-direction: column; align-items: center;">

          <div class="info_row">
            <div class="info_row_left">班级名称：</div>
            <div class="info_row_right">
              <el-input size="large" v-model="form.className" placeholder="请输入班级名称" />

            </div>
          </div>

          <div class="info_row">
            <div class="info_row_left">课程名称：</div>
            <div class="info_row_right">
              <el-autocomplete size="large" v-model="form.courseName" :fetch-suggestions="querySearch" clearable
                style="width:100%" class="inline-input w-50" placeholder="请输入授课课程名称" />

            </div>
          </div>

          <div class="info_row">
            <div class="info_row_left">开课学期：</div>
            <div class="info_row_right">
              <el-select size="large" style="width:100%" v-model="form.term" placeholder="请选择开课学期">
                <el-option v-for="option in termOptions" :key="option.value" :label="option.label"
                  :value="option.value"></el-option>
              </el-select>
            </div>
          </div>

          <div class="info_row">
            <div class="info_row_left">导入以往班课的任务</div>
            <div class="info_row_right">
              <el-switch v-model="form.import_course" />
            </div>
          </div>

          <div class="info_row" v-show="form.import_course">
            <div class="info_row_left">以往班课名称：</div>
            <div class="info_row_right">
              <el-autocomplete size="large" v-model="form.pre_course_name" :fetch-suggestions="querySearch2" clearable
                style="width:100%" class="inline-input w-50" placeholder="请选择以往的班课名称" />

            </div>
          </div>


          <div class="info_row" v-show="form.import_course">
            <div class="info_row_left">是否共享课程任务：</div>
            <div class="info_row_right">
              <el-switch v-model="form.share_files" />

              <div style="font-size:12px;color:gray;margin-left:10px">选中：<span
                  style="color:orange;">建议同一学期、同一课程、不同班级使用此功能</span></div>
              <div style="font-size:12px;color:gray;margin-left:10px">1、共享任务、任务文件、任务分数、任务权重，同父课程的任务同步增删；</div>
              <div style="font-size:12px;color:gray;margin-left:10px">2、无添加、删除任务权限，无上传任务文件权限</div>
              <div style="font-size:12px;color:gray;margin-left:10px;margin-top:10px">不选中：</div>
              <div style="font-size:12px;color:gray;margin-left:10px">只导入任务、任务文件，后续操作全部独立。</div>
            </div>
          </div>


        </div>
      </div>

      <div>
        <el-button type="primary" size="large" @click="handelCreateCourse" style="margin-top: 20px;">创建课程</el-button>
      </div>
    </el-card>
  </div>


</template>

<script lang="ts" setup>
import {  ref, onMounted } from 'vue'
import UploadCover from './uploadCover.vue'

import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { searchClassNamesApi, searchCourseNamesApi, createCourseApi } from '@/api/course'


const store = useStore()
const router = useRouter()

const form = ref({
  img: null,
  className: '',
  courseName: '',
  term: '',
  user_id: store.state.user.user_id,
  import_course: false,
  share_files: false,
  pre_course_name: '',
  pre_course_id: ''
});
const termOptions = ref([]);


interface RestaurantItem {
  value: string
  link: string
}
const courses = ref<RestaurantItem[]>([])
const classes = ref<RestaurantItem[]>([])

const querySearch = (queryString: string, cb: any) => {

  const results = queryString
    ? courses.value.filter(createFilter(queryString))
    : courses.value
  cb(results)

}
const querySearch2 = (queryString: string, cb: any) => {

  const results = queryString
    ? classes.value.filter(createFilter(queryString))
    : classes.value
  cb(results)

}
const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}
const loadAll = () => {
  const options = ref([])
  searchCourseNamesApi({ user_id: store.state.user.user_id }).then((res: any) => {
    for (const item of res.data) {
      options.value.push({ value: item, link: '' });
    }
  });
  courses.value = options.value;

  const options2 = ref([])
  searchClassNamesApi({ user_id: store.state.user.user_id }).then((res: any) => {
    for (const item of res.data) {
      options2.value.push({ value: item, link: '' });
    }
  });
  classes.value = options2.value;
}
onMounted(() => {
  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1;
  const options = [];

  // Determine the current term
  const currentTerm = currentMonth >= 9 ? 1 : 2;
  const currentAcademicYear = currentTerm === 1 ? `${currentYear}-${currentYear + 1}` : `${currentYear - 1}-${currentYear}`;

  // Generate options for the current and next 4 academic years
  for (let i = 0; i < 2; i++) {
    const year = currentYear + i - 1;
    options.push({ label: `${year}-${year + 1} 第一学期`, value: `${year}-${year + 1} 第一学期` });
    options.push({ label: `${year}-${year + 1} 第二学期`, value: `${year}-${year + 1} 第二学期` });
  }
  termOptions.value = options;
  loadAll()
});


const handelCreateCourse = () => {
  if (form.value.className.trim() === '') {
    ElMessage.error('班级名称不能为空');
    return;
  }
  if (form.value.courseName.trim() === '') {
    ElMessage.error('课程名称不能为空');
    return;
  }
  if (form.value.term.trim() === '') {
    ElMessage.error('开课学期不能为空');
    return;
  }
  if (form.value.import_course && form.value.pre_course_name.trim() === '') {
    ElMessage.error('请选择以往班课名称');
    return;
  }
  if (!form.value.import_course)
    form.value.pre_course_name = ''
  createCourseApi(form.value).then((res: any) => {
    if (res.code === 200) {

      ElMessage.success('创建课程成功');
      router.push('/teacher/home');

    } else {

      ElMessage.error('创建课程失败');
    }
  });

};

</script>

<style lang="scss" scoped>
.info-card {
  position: relative;
  width: 100vw;
  max-width: 1200px;
  height: auto;
  // max-height: 900px;

  align-content: center;
  margin-top: 10px;
}



.info_row {
  display: flex;
  justify-content: space-between;
  // width: 600px;
  margin-bottom: 30px;
  vertical-align: auto;
  align-self: center;
}

.info_row_left {
  width: 15vw;
  min-width: 100px;
  text-align: left;
  font-size: large;
}

.info_row_right {
  width: 20vw;
  min-width: 200px;
  text-align: left;
  font-size: large;

}
</style>